package cn.tianyigps.tianyigpsgatherchecker.dao;

import cn.tianyigps.tianyigpsgatherchecker.bean.BaseMessage;
import cn.tianyigps.tianyigpsgatherchecker.bean.Condition;
import cn.tianyigps.tianyigpsgatherchecker.bean.RuleModel;
import cn.tianyigps.tianyigpsgatherchecker.constant.UrlConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Repository
public class RuleDao {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RedisTemplate redisTemplate;

    public List<RuleModel<Condition>> getRules(String equipmentId, String type) {
        //需要校验的停车超时校验规则数据集合
        List<RuleModel<Condition>> list = (List<RuleModel<Condition>>) redisTemplate.opsForValue().get(type + equipmentId + "rule");
        //当缓存数据为空时调用Php接口获取数据
        if (!Optional.ofNullable(list).isPresent()) {
            //查询参数
            Map params = new HashMap(2);
            params.put("equipmentId", equipmentId);
            params.put("type", type);

            BaseMessage<Condition> message = null;
            try {
                message = restTemplate.getForObject(UrlConstant.RULE_LIST_URL, BaseMessage.class, params);
            } catch (ResourceAccessException e) {
                e.printStackTrace();
            }
            //查询出需要校验规则集合并放入redis缓存
            if (Optional.ofNullable(message).isPresent() && Optional.ofNullable(message.getData()).isPresent()) {
                list = message.getData().getItems();
                redisTemplate.opsForValue().set(type + equipmentId + "rule", list);
                Random random = new Random();
                redisTemplate.expire(type + equipmentId + "rule", random.nextInt(60 * 60) + 120 * 60, TimeUnit.SECONDS);
            }
        }
        return list;
    }
}
